package designplan

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"strconv"
	"oxy_server/model"
	"oxy_server/module/log"
	"oxy_server/res/dicserver/dimensions"
	"oxy_server/until"
	"time"

	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"
)

type (
	Designplan struct {
		ID                      bson.ObjectId           `json:"_id" bson:"_id"`
		DesignNumber            string                  `json:"designnumber" bson:"designnumber"`                       //设计号
		ModelName               string                  `json:"modelname" bson:"modelname"`                             //款名
		FactoryNumber           string                  `json:"factorynumber" bson:"factorynumber"`                     //工厂款号
		Brand                   string                  `json:"brand" bson:"brand"`                                     //品牌
		Gender                  string                  `json:"gender" bson:"gender"`                                   //性别
		ProductCategory         string                  `json:"productcategory" bson:"productcategory"`                 //产品大类
		ProductKind             string                  `json:"productkind" bson:"productkind"`                         //品类
		Year                    string                  `json:"year" bson:"year"`                                       //年份
		Season                  string                  `json:"season" bson:"season"`                                   //季节
		Color                   []string                `json:"color" bson:"color"`                                     //颜色
		DesignPic               []string                `json:"designpic" bson:"designpic"`                             //设计稿
		Designer                string                  `json:"designer" bson:"designer"`                               //设计师
		Batch                   string                  `json:"batch" bson:"batch"`                                     //批次
		Provider                string                  `json:"provider" bson:"provider"`                               //供应商
		FactoryCost             string                  `json:"factorycost" bson:"factorycost"`                         //工厂报价
		TargetCost              string                  `json:"targetcost" bson:"targetcost"`                           //目标成本
		ReferenceRatio          string                  `json:"referenceratio" bson:"referenceratio"`                   //参考倍率
		FactoryPrice            string                  `json:"factoryprice" bson:"factoryprice"`                       //工厂吊牌价
		TargetPrice             string                  `json:"targetprice" bson:"targetprice"`                         //目标牌价
		OrderQuantity           string                  `json:"orderquantity" bson:"orderquantity"`                     //品牌预定数量
		ProductProperty         string                  `json:"productproperty" bson:"productproperty"`                 //产品属性
		Note                    string                  `json:"note" bson:"note"`                                       //备注
		Order                   []Order                 `json:"order" bson:"order"`                                     //预订
		SizeSpecificationsTable []string                `json:"sizespecificationstable" bson:"sizespecificationstable"` //版师 组
		SizeRecommendationTable []string                `json:"sizerecommendationtable" bson:"sizerecommendationtable"` // 版师组
		Pattern                 []string                `json:"pattern" bson:"pattern"`                                 // 版师组 纸样
		PropertyStatus          int                     `json:"propertystatus" bson:"propertystatus"`                   //产品属性编辑状态
		EditerStatus            int                     `json:"editerstatus" bson:"editerstatus"`                       //版师状态
		Picture                 []string                `json:"picture" bson:"picture"`
		LargeNumber             string                  `json:"largenumber" bson:"largenumber"`               //大货号
		Type                    string                  `json:"type" bson:"type"`                             //类型
		EditerCompleteTime      time.Time               `json:"editercompletetime" bson:"editercompletetime"` // 尺码推荐完成时间
		Tabs                    string                  `json:"tabs" bson:"tabs"`                             // 物料单
		Dimensions              []dimensions.Dimensions `json:"dimensions" bson:"dimensions"`                 // 设计组版师 尺寸规格表数据
		RecommendedSize         []RecommendSize         `json:"recommendsize" bson:"recommendsize"`           // 设计组版师 尺码推荐表

	}
	insertdesignplan struct {
		Brand                   string                  `json:"brand" bson:"brand"`                     //品牌
		DesignNumber            string                  `json:"designnumber" bson:"designnumber"`       //设计号
		ModelName               string                  `json:"modelname" bson:"modelname"`             //款名
		FactoryNumber           string                  `json:"factorynumber" bson:"factorynumber"`     //工厂款号
		Gender                  string                  `json:"gender" bson:"gender"`                   //性别
		ProductCategory         string                  `json:"productcategory" bson:"productcategory"` //产品大类
		ProductKind             string                  `json:"productkind" bson:"productkind"`         //品类
		Year                    string                  `json:"year" bson:"year"`                       //年份
		Season                  string                  `json:"season" bson:"season"`                   //季节
		Color                   []string                `json:"color" bson:"color"`                     //颜色
		DesignPic               []string                `json:"designpic" bson:"designpic"`             //设计稿
		Designer                string                  `json:"designer" bson:"designer"`               //设计师
		Batch                   string                  `json:"batch" bson:"batch"`                     //批次
		Provider                string                  `json:"provider" bson:"provider"`               //供应商
		FactoryCost             string                  `json:"factorycost" bson:"factorycost"`         //工厂报价
		TargetCost              string                  `json:"targetcost" bson:"targetcost"`           //目标成本
		ReferenceRatio          string                  `json:"referenceratio" bson:"referenceratio"`   //参考倍率
		FactoryPrice            string                  `json:"factoryprice" bson:"factoryprice"`       //工厂吊牌价
		TargetPrice             string                  `json:"targetprice" bson:"targetprice"`         //目标牌价
		OrderQuantity           string                  `json:"orderquantity" bson:"orderquantity"`     //品牌预定数量
		ProductProperty         string                  `json:"productproperty" bson:"productproperty"` //产品属性
		Note                    string                  `json:"note" bson:"note"`                       //备注
		Order                   []Order                 `json:"order" bson:"order"`                     //预订
		SizeSpecificationsTable []string                `json:"sizespecificationstable" bson:"sizespecificationstable"`
		SizeRecommendationTable []string                `json:"sizerecommendationtable" bson:"sizerecommendationtable"`
		Pattern                 []string                `json:"pattern" bson:"pattern"`               // 版师组 纸样
		PropertyStatus          int                     `json:"propertystatus" bson:"propertystatus"` //产品属性编辑状态
		EditerStatus            int                     `json:"editerstatus" bson:"editerstatus"`     //版师状态
		Picture                 []string                `json:"picture" bson:"picture"`
		LargeNumber             string                  `json:"largenumber" bson:"largenumber"`               //大货号
		Type                    string                  `json:"type" bson:"type"`                             //类型
		EditerCompleteTime      time.Time               `json:"editercompletetime" bson:"editercompletetime"` // 尺码推荐完成时间
		Tabs                    string                  `json:"tabs" bson:"tabs"`                             // 物料单
		Dimensions              []dimensions.Dimensions `json:"dimensions" bson:"dimensions"`                 // 设计组版师 尺寸规格表数据
		RecommendedSize         []RecommendSize         `json:"recommendsize" bson:"recommendsize"`           // 设计组版师 尺寸规格表数据
	}
	Order struct {
		Brand       string   `json:"brand" bson:"brand"`             //品牌
		Number      string   `json:"number" bson:"number"`           //流水号
		Count       string   `json:"count" bson:"count"`             //数量
		Price       string   `json:"price" bson:"price"`             //零售价
		LargeNumber string   `json:"largenumber" bson:"largenumber"` //大货号
		Color       []string `json:"color" bson:"color"`             //颜色
		Note        string   `json:"note" bson:"note"`               //备注
	}

	UpdateProductTabs struct {
		LargeCargoNumber string `json:"largecargonumber" bson:"largecargonumber"` //大货号
		Tabs             string `json:"tabs" bson:"tabs"`                         // 物料单

	}
	RecommendSize struct {
		Height string `json:"height" bson:"height"`
		KG40   string `json:"KG40" bson:"KG40"`
		KG42   string `json:"KG42" bson:"KG42"`
		KG45   string `json:"KG45" bson:"KG45"`
		KG47   string `json:"KG47" bson:"KG47"`
		KG50   string `json:"KG50" bson:"KG50"`
		KG52   string `json:"KG52" bson:"KG52"`
		KG55   string `json:"KG55" bson:"KG55"`
		KG57   string `json:"KG57" bson:"KG57"`
		KG60   string `json:"KG60" bson:"KG60"`
		KG62   string `json:"KG62" bson:"KG62"`
		KG65   string `json:"KG65" bson:"KG65"`
		KG67   string `json:"KG67" bson:"KG67"`
		KG70   string `json:"KG70" bson:"KG70"`
		KG72   string `json:"KG72" bson:"KG72"`
		KG75   string `json:"KG75" bson:"KG75"`
		KG77   string `json:"KG77" bson:"KG77"`
		KG80   string `json:"KG80" bson:"KG80"`
		KG82   string `json:"KG82" bson:"KG82"`
		KG85   string `json:"KG85" bson:"KG85"`
		KG87   string `json:"KG87" bson:"KG87"`
		KG90   string `json:"KG90" bson:"KG90"`
		KG95   string `json:"KG95" bson:"KG95"`
	}
)

type OXYDesignPlanData struct{}

func NewOXYDesignPlanData() *OXYDesignPlanData {
	designPlanData := &OXYDesignPlanData{}
	return designPlanData
}

func (opd *OXYDesignPlanData) GetDesignPlanListHandler(c echo.Context) error {
	log.Info("GetDesignPlanListHandler")
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_plan"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, count, err := model.DB().Query(M, currentpage, perpage)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []Designplan{}
	query.All(&ps)

	str, err := json.Marshal(ps)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  string(str),
		"count": count,
	})

	return nil
}

func (opd *OXYDesignPlanData) GetDesignPlanInfoHandler(c echo.Context) error {
	log.Info("GetDesignPlanInfoHandler")
	id := c.QueryParam("id")
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_plan"
	query, err := model.DB().QueryOne(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	p := Designplan{}
	query.One(&p)
	str, err := json.Marshal(p)
	if err != nil {
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"data": string(str),
	})

	return nil
}

func (opd *OXYDesignPlanData) AddDesignPlanHandler(c echo.Context) error {
	o := &insertdesignplan{}
	if err := c.Bind(o); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_plan"
	err := model.DB().Insert(o)
	if err != nil {
		log.Error("插入出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	// c.JSON(200, map[string]interface{}{
	// 	"msg": "success",
	// })
	M := bson.M{}
	data, err1 := bson.Marshal(o)
	if err1 != nil {
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err1
	}
	err = bson.Unmarshal(data, &M)
	if err != nil {
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, err := model.DB().QueryOne(M)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	p1 := Designplan{}
	query.One(&p1)
	str, err := json.Marshal(p1)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"data": string(str),
	})

	return nil
}

func (opd *OXYDesignPlanData) AddDesignsPlanHandler(c echo.Context) error {
	datas := &[]insertdesignplan{}
	if err := c.Bind(datas); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_plan"
	for _, o := range *datas {
		err := model.DB().Insert(o)
		if err != nil {
			log.Error("插入出错", err)
			c.JSON(404, map[string]interface{}{
				"msg": "error",
			})
			return err
		}

	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

func (opd *OXYDesignPlanData) UpdateDesignPlanOrderHandler(c echo.Context) error {
	id := c.QueryParam("id")
	o := &[]Order{}
	if err := c.Bind(o); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_plan"
	selector := bson.M{"_id": bson.ObjectIdHex(id)}
	data := bson.M{"$set": bson.M{"order": o}}
	err := model.DB().Update(selector, data)
	if err != nil {
		log.Error("更新出错,UpdateDesignPlanOrderHandler", err)
		c.JSON(404, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

func (opd *OXYDesignPlanData) UpdateDesignPlanHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("UpdateDesignPlanHandler", id)

	o := &insertdesignplan{}
	if err := c.Bind(o); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_plan"
	p := Designplan{}
	query, err := model.DB().QueryOne(bson.M{"_id": bson.ObjectIdHex(id)})
	query.One(&p)
	s, err := json.Marshal(p)
	bufbody := bytes.NewBuffer(s)
	c.Request().Body = ioutil.NopCloser(bufbody)

	err = model.DB().Update(bson.M{"_id": bson.ObjectIdHex(id)}, o)

	//更新过会组状态
	model.DB().Document = "product_plan"
	selector := bson.M{"designplanid": id}
	data := bson.M{"$set": bson.M{"designediterstatus": o.EditerStatus}}
	_, err = model.DB().UpdateAll(selector, data)
	if err != nil {
		log.Error("更新出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

func (opd *OXYDesignPlanData) DelDesignPlanHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("DelDesignPlanHandler", id)
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_plan"
	p := Designplan{}
	query, err := model.DB().QueryOne(bson.M{"_id": bson.ObjectIdHex(id)})
	query.One(&p)
	s, err := json.Marshal(p)
	bufbody := bytes.NewBuffer(s)
	c.Request().Body = ioutil.NopCloser(bufbody)

	err = model.DB().Remove(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		log.Error("删除出错 design_plan", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Document = "design_property"
	err = model.DB().Remove(bson.M{"designplanid": id})
	if err != nil {
		log.Error("删除出错 design_property", err)
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

func (opd *OXYDesignPlanData) UpdateProductTabsHandler(c echo.Context) error {
	data := &[]UpdateProductTabs{}
	if err := c.Bind(data); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	var result []string
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan"
	for _, item := range *data {
		err := model.DB().Update(bson.M{"largecargonumber": item.LargeCargoNumber}, bson.M{"$set": bson.M{"tabs": item.Tabs}})
		if err != nil {
			result = append(result, item.LargeCargoNumber)
			log.Error("设计组向生产组更新物料单数据失败"+item.LargeCargoNumber, err)
		}
	}
	if len(result) > 0 {
		c.JSON(200, map[string]interface{}{
			"msg":  "error",
			"info": result,
		})
	} else {
		c.JSON(200, map[string]interface{}{
			"msg": "success",
		})
	}
	return nil
}
